package com.weaver.drools.dao.common.impl;

import org.hibernate.SQLQuery;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.transform.Transformers;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.util.Assert;
import com.weaver.drools.common.utils.PageTag;
import com.weaver.drools.dao.common.CommonBaseDao;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.sql.Connection;
import java.util.List;
/**
 * 
 *  @application name: 
 *  @author: zhouxinlei 
 * @param <R>
 *  @time：2018年6月27日
 *  @version：ver 1.1
 */
@SuppressWarnings("deprecation")
public class CommonBaseDaoImpl<T, ID extends Serializable> extends SimpleJpaRepository<T,ID>
        implements CommonBaseDao<T,ID> {

    private final EntityManager entityManager;
    //父类没有不带参数的构造方法，这里手动构造父类
    public CommonBaseDaoImpl(Class<T> domainClass, EntityManager entityManager) {
        super(domainClass, entityManager);
        this.entityManager = entityManager;
    }
    
	@SuppressWarnings("unchecked")
	public List<T> listBySQL(String sql, Class<T> cls) {
		Query query =entityManager.createNativeQuery(sql,cls);
		return query.getResultList();
	}

	
	public String StringBySQL(String sql) {
		Query query =entityManager.createNativeQuery(sql);
		return query.getResultList().get(0).toString();
	}

	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List findListBySql(String sql) {
		Query query = entityManager.createNativeQuery(sql);
	    query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);  
	    List list = query.getResultList();
		return list;
	}

	public Long findIdBySQL(String sql) {
		Object object=entityManager.createNativeQuery(sql).getResultList();
		Long count=(Long)object;
		return count;
	}
	@SuppressWarnings("unchecked")
	public PageTag<T> findPage(int currentNum,String hql, String countHql) {
		Assert.notNull(hql, "findPage()  hql must not be null!");
		PageTag<T> page = new PageTag<T>();
		Query query = entityManager.createQuery(hql);
		Long totalCount = (long) -1;
		
		if(countHql == null || countHql ==""){
			totalCount = (long) query.getResultList().size();
		}else{
			Query countQuery = this.entityManager.createQuery(countHql,Long.class);
			totalCount = (Long) countQuery.getSingleResult();
		}
        	
		if (page != null) { // 分页
			page.setPageNo(currentNum);
			query.setFirstResult(page.getFirst() - 1);
			if (page.getPageSize() != -1)
				query.setMaxResults(page.getPageSize());
		}
		page.setResult(query.getResultList());
		page.setTotalCount(totalCount);
		return page;
	}

	@SuppressWarnings("unchecked")
	public List<T> findListByhql(String hql) {
		Assert.notNull(hql, "findListByhql  hql must not be null!");
		Query query = entityManager.createQuery(hql);
		List<T> list = query.getResultList();
		return list;
	}

	@SuppressWarnings("unchecked")
	public T findEntity(String hql) {
		return (T) entityManager.createQuery(hql).getSingleResult();
	}

	@Override
	public T saveOrUpdate(T entity) {
		// TODO Auto-generated method stub
		return super.saveAndFlush(entity);
	}

	public Connection getConnection() throws Exception{
		SessionImplementor session =entityManager.unwrap(SessionImplementor.class);
		return session.connection();
	}

}
